package com.simon.netty.demo1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

/**
 * Created by changf on 2017/7/14.
 */
public class EchoServer2InHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server in 2");
        ByteBuf req= (ByteBuf) msg;
        byte[] byteBuf=new byte[req.readableBytes()];
        req.readBytes(byteBuf);

        String body=new String(byteBuf,"UTF-8");
        System.out.println("server read data:"+body);

        //向客户端回写数据
        System.out.println("server send data to client");
        String currentTime=new Date(System.currentTimeMillis()).toString();
        ByteBuf resp= Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
    }
}
